package org.openapi.controller;

import com.alibaba.fastjson2.JSON;
import org.openapi.common.ApiResult;
import org.openapi.consts.ApiConst;
import org.openapi.consts.ExchangeMode;
import org.openapi.domain.ApiExchange;
import org.openapi.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 开放数据接口
 */
public class OpenExchangeController
{
    @Autowired
    private IApiLoaderService apiLoaderService;

    @Autowired
    private IOpenExchangeService openExchangeService;

    /**
     * 一层路由请求
     */
    @RequestMapping("/{v1}")
    public void rest1(HttpServletRequest request, HttpServletResponse response,  @PathVariable("v1") String v1, @RequestBody String dataStr)
    {
        process(request, response,  "/"+v1, dataStr);
    }

    /**
     * 二级路由请求
     * @param request
     * @param response
     * @param v1
     * @param v2
     * @param dataStr
     */
    @RequestMapping("/{v1}/{v2}")
    public void rest2(HttpServletRequest request, HttpServletResponse response, @PathVariable("v1") String v1,  @PathVariable("v2") String v2, @RequestBody String dataStr)
    {
        process(request, response,"/"+v1+"/"+v2, dataStr);
    }

    /**
     * 通用处理方法
     * @param request 请求对象
     * @param response 响应对象
     * @param uri 绑定的URL，对应接口配置
     * @param dataStr 请求正文
     */
    protected void process(HttpServletRequest request, HttpServletResponse response, String uri, String dataStr) {
        ApiExchange exchange = apiLoaderService.getExchange(uri);
        try {
            if(exchange == null){
                response.sendError(404);
                return;
            }

            Map<String,Object> params = new HashMap<>();
            Enumeration<String> pns = request.getParameterNames();
            while(pns.hasMoreElements()){
                String pn = pns.nextElement();
                params.put(pn, request.getParameter(pn));
            }
            ApiResult result;
            if(ExchangeMode.READ.equalsIgnoreCase(exchange.getMode())){
                result = openExchangeService.doRead(exchange, JSON.toJSONString(params));
            }else{
                result = openExchangeService.doWrite(exchange, dataStr);
            }
            if(result.getCode() == ApiConst.HTTP_OK){
                response.getWriter().println(result.getMsg());
            }else{
                response.sendError(result.getCode());
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
